<template>
  <div class="publish">
    <SwipePagination v-model="page" :can-swipe="false" :disable-transition="isUpdate">
      <MediaInput @to-edit="page = 2"></MediaInput>
      <template #page-2>
        <PublishEditor @complete="revert" @cancel="cancelEdit"></PublishEditor>
      </template>
    </SwipePagination>
  </div>
</template>

<script setup>
import { onActivated, onDeactivated, ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { usePublishStore } from '@/store/publish'
import i18n from '@/i18n'
import asyncCompWithLoading from '@/utils/async-comp-with-loading'

const SwipePagination = asyncCompWithLoading(() => import('@/components/swipe/SwipePagination.vue'))
const MediaInput = asyncCompWithLoading(() => import('./MediaInput.vue'))
const PublishEditor = asyncCompWithLoading(() => import('@/components/publish/PublishEditor.vue'))

const publishStore = usePublishStore()
const { isUpdate } = storeToRefs(publishStore)
const { cancelUpload, clear } = publishStore

const page = ref(1)

let pageResetTimerId
function revert() {
  if (pageResetTimerId) return
  if (isUpdate.value) {
    pageResetTimerId = setTimeout(() => setPage(1), 300)
  } else {
    setPage(1)
  }
  clear()
}

function cancelEdit() {
  cancelUpload()
  revert()
}

// 被喚起時要先判斷是否需要直接導向何方
const accountStore = useAccountStore()
const { userData } = storeToRefs(accountStore)
const { $alert } = usePopupDialogStore()
const router = useRouter()
onActivated(() => {
  // 判別是否是創作者，不是的話將頁面導致成為創作者頁面
  if (!userData.value.is_creator) {
    $alert({
      title: i18n.global.t('content.beCreator.notYet'),
      content: i18n.global.t('content.beCreator.toBe'),
      confirm: () => {
        router.replace({
          path: 'mine/creator-faq',
        })
      },
      showClose: false,
    }).open()
    return
  }

  // 判斷是否是更新帖子，是的話直接進入編輯頁面
  if (isUpdate.value) {
    setPage(2)
  }
})

onDeactivated(() => {
  if (isUpdate.value) {
    revert()
  }
})

function setPage(v) {
  clearTimeout(pageResetTimerId)
  pageResetTimerId = undefined
  page.value = v
}
</script>

<style lang="scss" scoped>
.publish {
  width: 100%;
  height: 100%;
}
</style>
